package net.lijingye.education.controller;

import net.lijingye.education.entity.Friend;
import net.lijingye.education.entity.FriendRequest;
import net.lijingye.education.entity.Tweet;
import net.lijingye.education.entity.User;
import net.lijingye.education.exception.DaoException;
import net.lijingye.education.exception.FriendRequestNotExistsException;
import net.lijingye.education.exception.FriendshipNotExistsException;
import net.lijingye.education.exception.ObjectNotExistsException;
import net.lijingye.education.request.PutFriendRequestRequest;
import net.lijingye.education.response.BaseResponse;
import net.lijingye.education.response.ErrorResponse;
import net.lijingye.education.response.SuccessResponse;
import net.lijingye.education.response.meta.FriendRequestNotExistsMeta;
import net.lijingye.education.response.meta.FriendshipNotExistsMeta;
import net.lijingye.education.response.meta.JSONParameterErrorMeta;
import net.lijingye.education.response.meta.ObjectNotExistsMeta;
import net.lijingye.education.service.UserService;
import net.lijingye.education.util.CommonUtil;
import net.lijingye.education.vo.FriendRequestVO;
import net.lijingye.education.vo.FriendVO;
import net.lijingye.education.vo.PageVO;
import net.lijingye.education.vo.TweetVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by LijingYe on 2016/3/27.
 */
@RestController
public class MyFriendController extends BaseController {
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/my/friends", method = RequestMethod.GET)
    public BaseResponse getMyFriends(@RequestHeader("Authorization") String accessToken, @RequestParam(value = "page", required = false) String page) throws DaoException {
        try {
            User user = userService.getUserByAccessToken(accessToken);
            List<Friend> friendList = user.getFriendList();
            List<FriendVO> friendVOList = new ArrayList<>();
            friendList.forEach(friend -> {
                friendVOList.add(new FriendVO(friend));
            });
            return CommonUtil.splitPage(friendVOList, page, super.getPageSize());
        } catch (ObjectNotExistsException e) {
            System.out.println(e.getMessage());
            return new ErrorResponse(new ObjectNotExistsMeta());
        }
    }

    @RequestMapping(value = "/my/friends/{friendId}", method = RequestMethod.DELETE)
    public BaseResponse deleteMyFriends(@RequestHeader("Authorization") String accessToken, @PathVariable String friendId) throws DaoException {
        try {
            User user = userService.getUserByAccessToken(accessToken);
            userService.deleteFriend(user.getId(), friendId);
            return new SuccessResponse(null);
        } catch (ObjectNotExistsException e) {
            System.out.println(e.getMessage());
            return new ErrorResponse(new ObjectNotExistsMeta());
        } catch (FriendshipNotExistsException e) {
            System.out.println(e.getMessage());
            return new ErrorResponse(new FriendshipNotExistsMeta());
        }
    }

    @RequestMapping(value = "/my/friends/requests", method = RequestMethod.GET)
    public BaseResponse getMyFriendRequests(@RequestHeader("Authorization") String accessToken, @RequestParam(value = "page", required = false) String page) throws DaoException {
        try {
            User user = userService.getUserByAccessToken(accessToken);
            List<FriendRequest> friendRequestList = user.getFriendRequestList();
            List<FriendRequestVO> friendRequestVOList = new ArrayList<>();
            friendRequestList.forEach(friendRequest -> {
                if (friendRequest.getIsAccept() == 0) {
                    friendRequestVOList.add(new FriendRequestVO(friendRequest));
                }
            });
            return CommonUtil.splitPage(friendRequestVOList, page, super.getPageSize());
        } catch (ObjectNotExistsException e) {
            System.out.println(e.getMessage());
            return new ErrorResponse(new ObjectNotExistsMeta());
        }
    }

    @RequestMapping(value = "/my/friends/requests/{requestId}", method = RequestMethod.PUT)
    public BaseResponse putMyFriendRequest(@RequestHeader("Authorization") String accessToken, @PathVariable String requestId, @Valid @RequestBody PutFriendRequestRequest putFriendRequestRequest, BindingResult result) throws DaoException {
        if (result.hasErrors()) {
            return new ErrorResponse(new JSONParameterErrorMeta());
        }
        try {
            User user = userService.getUserByAccessToken(accessToken);
            userService.editFriendRequest(user, requestId, putFriendRequestRequest.getAccept());
            return new SuccessResponse(null);
        } catch (ObjectNotExistsException e) {
            System.out.println(e.getMessage());
            return new ErrorResponse(new ObjectNotExistsMeta());
        } catch (FriendRequestNotExistsException e) {
            System.out.println(e.getMessage());
            return new ErrorResponse(new FriendRequestNotExistsMeta());
        }
    }

    @RequestMapping(value = "/my/friends/tweets", method = RequestMethod.GET)
    public BaseResponse getMyFriendsTweets(@RequestHeader("Authorization") String accessToken, @RequestParam(value = "page", required = false) String page) throws DaoException {
        try {
            User user = userService.getUserByAccessToken(accessToken);
            List<Friend> friendList = user.getFriendList();
            List<Tweet> myFriendsTweetList = new ArrayList<>();
            friendList.forEach(friend -> {
                System.out.print(friend.getFriend().getId()+" ");
                System.out.println(friend.getFriend().getTweetList().size());
                myFriendsTweetList.addAll(friend.getFriend().getTweetList());
            });
            myFriendsTweetList.sort((Tweet o1, Tweet o2) -> {
                if (o1.getTime().before(o2.getTime())) {
                    return 1;
                }
                if (o1.getTime().after(o2.getTime())) {
                    return -1;
                }
                return 0;
            });
            List<TweetVO> myFriendsTweetVOList = new ArrayList<>();
            for (Tweet tweet : myFriendsTweetList) {
                User author = userService.getUserById(tweet.getUserId());
                myFriendsTweetVOList.add(new TweetVO(tweet, author));
            }
            return CommonUtil.splitPage(myFriendsTweetVOList, page, super.getPageSize());
        } catch (ObjectNotExistsException e) {
            System.out.println(e.getMessage());
            return new ErrorResponse(new ObjectNotExistsMeta());
        }
    }
}
